const User = require('../models/User');
const { generateToken } = require('../config/jwt');
const { catchAsync } = require('../utils/errorHandler');

// 注册新用户
exports.register = catchAsync(async (req, res) => {
  const { username, email, password, role, age } = req.body;

  // 检查用户是否已存在
  const existingUser = await User.findOne({ $or: [{ email }, { username }] });
  if (existingUser) {
    return res.status(400).json({
      success: false,
      message: '用户名或邮箱已被注册',
    });
  }

  // 创建新用户
  const user = await User.create({
    username,
    email,
    password,
    role,
    age,
  });

  // 生成JWT令牌
  const token = generateToken(user._id);

  // 返回用户信息（不包含密码）
  res.status(201).json({
    success: true,
    message: '用户注册成功',
    data: {
      user: {
        _id: user._id,
        username: user.username,
        email: user.email,
        role: user.role,
        avatar: user.avatar,
        age: user.age,
      },
      token,
    },
  });
});

// 用户登录
exports.login = catchAsync(async (req, res) => {
  const { email, password } = req.body;

  // 检查用户是否提供了邮箱和密码
  if (!email || !password) {
    return res.status(400).json({
      success: false,
      message: '请提供邮箱和密码',
    });
  }

  // 查找用户并包含密码字段
  const user = await User.findOne({ email }).select('+password');

  // 检查用户是否存在
  if (!user) {
    return res.status(401).json({
      success: false,
      message: '邮箱或密码不正确',
    });
  }

  // 检查密码是否正确
  const isPasswordCorrect = await user.comparePassword(password);
  if (!isPasswordCorrect) {
    return res.status(401).json({
      success: false,
      message: '邮箱或密码不正确',
    });
  }

  // 更新最后登录时间
  user.lastLogin = Date.now();
  await user.save({ validateBeforeSave: false });

  // 生成JWT令牌
  const token = generateToken(user._id);

  // 返回用户信息（不包含密码）
  res.status(200).json({
    success: true,
    message: '登录成功',
    data: {
      user: {
        _id: user._id,
        username: user.username,
        email: user.email,
        role: user.role,
        avatar: user.avatar,
        age: user.age,
        learningProgress: user.learningProgress,
        preferences: user.preferences,
      },
      token,
    },
  });
});

// 获取当前用户信息
exports.getCurrentUser = catchAsync(async (req, res) => {
  const user = await User.findById(req.user.id);

  if (!user) {
    return res.status(404).json({
      success: false,
      message: '用户不存在',
    });
  }

  res.status(200).json({
    success: true,
    data: {
      user: {
        _id: user._id,
        username: user.username,
        email: user.email,
        role: user.role,
        avatar: user.avatar,
        age: user.age,
        bio: user.bio,
        learningProgress: user.learningProgress,
        preferences: user.preferences,
        createdAt: user.createdAt,
        lastLogin: user.lastLogin,
      },
    },
  });
});

// 更新用户信息
exports.updateUser = catchAsync(async (req, res) => {
  const { username, avatar, bio, age, preferences } = req.body;

  // 查找并更新用户
  const user = await User.findByIdAndUpdate(
    req.user.id,
    {
      username,
      avatar,
      bio,
      age,
      preferences,
    },
    {
      new: true, // 返回更新后的文档
      runValidators: true, // 运行验证器
    }
  );

  if (!user) {
    return res.status(404).json({
      success: false,
      message: '用户不存在',
    });
  }

  res.status(200).json({
    success: true,
    message: '用户信息更新成功',
    data: {
      user: {
        _id: user._id,
        username: user.username,
        email: user.email,
        role: user.role,
        avatar: user.avatar,
        age: user.age,
        bio: user.bio,
        preferences: user.preferences,
      },
    },
  });
});

// 更新用户密码
exports.updatePassword = catchAsync(async (req, res) => {
  const { currentPassword, newPassword } = req.body;

  // 查找用户并包含密码字段
  const user = await User.findById(req.user.id).select('+password');

  // 检查当前密码是否正确
  const isPasswordCorrect = await user.comparePassword(currentPassword);
  if (!isPasswordCorrect) {
    return res.status(401).json({
      success: false,
      message: '当前密码不正确',
    });
  }

  // 更新密码
  user.password = newPassword;
  await user.save();

  // 生成新的JWT令牌
  const token = generateToken(user._id);

  res.status(200).json({
    success: true,
    message: '密码更新成功',
    data: { token },
  });
});

// 获取用户学习进度
exports.getLearningProgress = catchAsync(async (req, res) => {
  const user = await User.findById(req.user.id)
    .populate('learningProgress.completedProjects', 'title thumbnail')
    .populate('learningProgress.completedChallenges', 'title difficulty category');

  if (!user) {
    return res.status(404).json({
      success: false,
      message: '用户不存在',
    });
  }

  res.status(200).json({
    success: true,
    data: {
      learningProgress: user.learningProgress,
    },
  });
});

// 更新用户学习进度
exports.updateLearningProgress = catchAsync(async (req, res) => {
  const { level, experience, completedProject, completedChallenge, badge } = req.body;

  // 查找用户
  const user = await User.findById(req.user.id);

  if (!user) {
    return res.status(404).json({
      success: false,
      message: '用户不存在',
    });
  }

  // 更新学习进度
  if (level) user.learningProgress.level = level;
  if (experience) user.learningProgress.experience = experience;
  
  // 添加已完成的项目
  if (completedProject && !user.learningProgress.completedProjects.includes(completedProject)) {
    user.learningProgress.completedProjects.push(completedProject);
  }
  
  // 添加已完成的挑战
  if (completedChallenge && !user.learningProgress.completedChallenges.includes(completedChallenge)) {
    user.learningProgress.completedChallenges.push(completedChallenge);
  }
  
  // 添加徽章
  if (badge) {
    user.learningProgress.badges.push({
      name: badge.name,
      description: badge.description,
      dateEarned: new Date(),
    });
  }

  await user.save();

  res.status(200).json({
    success: true,
    message: '学习进度更新成功',
    data: {
      learningProgress: user.learningProgress,
    },
  });
});

// 获取用户列表（仅管理员可用）
exports.getAllUsers = catchAsync(async (req, res) => {
  // 分页参数
  const page = parseInt(req.query.page, 10) || 1;
  const limit = parseInt(req.query.limit, 10) || 10;
  const skip = (page - 1) * limit;

  // 查询参数
  const filter = {};
  if (req.query.role) filter.role = req.query.role;
  if (req.query.isActive !== undefined) filter.isActive = req.query.isActive === 'true';

  // 执行查询
  const users = await User.find(filter)
    .skip(skip)
    .limit(limit)
    .select('username email role avatar age isActive createdAt lastLogin');

  // 获取总数
  const total = await User.countDocuments(filter);

  res.status(200).json({
    success: true,
    data: {
      users,
      pagination: {
        total,
        page,
        limit,
        pages: Math.ceil(total / limit),
      },
    },
  });
});